<template>
  <div class="tray-info">
    <div
      class="scale-block"
      :style="{
        transform: `scale(${trayConfig.scale / 100})`,
      }"
    >
      <div :style="canvasStyle" class="canvas">
        <div class="tip">顶面</div>
        <DragBlock
          side="0"
          className="tray"
          @drop="dragHandle"
          @dragover="dragoverHandle"
          @mousedown="clickHandle"
          :component="frontComponent"
          shapeType="tray"
          :style="trayStyle(0)"
          elId="tray-front"
        >
          <div class="tray-tie">
            <div
              :class="['tie-x', selectTie.id == tie.id ? 'selected' : '']"
              v-for="(tie, idx) of trayConfig.tieX"
              :key="idx"
              :style="{
                top: tie.y + 'px',
                left: tie.x + 'px',
                height: trayConfig.tieWidth + 'px',
              }"
              @mousedown.stop="tieDown($event, tie, 'x')"
              @mouseup.stop="tieUp($event, tie)"
              @mouseout.stop="tieUp($event, tie)"
              @contextmenu="handleContextmenu"
            ></div>
            <div
              :class="['tie-y', selectTie.id == tie.id ? 'selected' : '']"
              v-for="(tie, idx) of trayConfig.tieY"
              :key="idx"
              :style="{
                top: tie.y + 'px',
                left: tie.x + 'px',
                width: trayConfig.tieWidth + 'px',
              }"
              @mousedown.stop="tieDown($event, tie, 'y')"
              @mouseup.stop="tieUp($event, tie)"
              @mouseout.stop="tieUp($event, tie)"
              @contextmenu="handleContextmenu"
            ></div>
          </div>
        </DragBlock>
      </div>
      <div :style="canvasStyle" class="canvas">
        <div class="tip">底面</div>
        <DragBlock
          side="1"
          className="tray"
          @drop="dragHandle"
          @dragover="dragoverHandle"
          @mousedown="clickHandle"
          :component="oppositeComponent"
          shapeType="tray"
          :style="trayStyle(1)"
          elId="tray-opposite"
        >
          <div class="tray-tie">
            <div
              :class="['tie-x', selectTie.id == tie.id ? 'selected' : '']"
              v-for="(tie, idx) of trayConfig.tieX"
              :key="idx"
              :style="{
                top: tie.y + 'px',
                left: tie.x + 'px',
                height: trayConfig.tieWidth + 'px',
              }"
              @mousedown.stop="tieDown($event, tie, 'x')"
              @mouseup.stop="tieUp($event, tie)"
              @mouseout.stop="tieUp($event, tie)"
            ></div>
            <div
              :class="['tie-y', selectTie.id == tie.id ? 'selected' : '']"
              v-for="(tie, idx) of trayConfig.tieY"
              :key="idx"
              :style="{
                top: tie.y + 'px',
                left: tie.x + 'px',
                width: trayConfig.tieWidth + 'px',
              }"
              @mousedown.stop="tieDown($event, tie, 'y')"
              @mouseup.stop="tieUp($event, tie)"
              @mouseout.stop="tieUp($event, tie)"
            ></div>
          </div>
        </DragBlock>
      </div>
    </div>
    <Teleport to="body">
      <div class="r-menu" :style="position" v-show="menuShow" id="tie-menu">
        <div class="item" @click="changeLock()">
          <span class="icon"
            ><Lock v-if="selectTie.lock" /><Unlock v-else
          /></span>
          <span class="label">{{ selectTie.lock ? "解锁" : "锁定" }}</span>
        </div>
      </div>
    </Teleport>
  </div>
</template>
<script setup>
import { ref, computed, reactive, onMounted, onBeforeMount } from "vue";
import editStore from "@/store/editStore";
import DragBlock from "./dragBlock.vue";
import trayImg from "@/assets/images/edit/tray.png";
import { getGUID } from "@/utils";
import { Lock, Unlock } from "@element-plus/icons-vue";

const store = editStore();
let menuShow = ref(false);
let selectTie = ref({});
let position = reactive({ left: 0, top: 0 });
let trayConfig = computed(() => store.trayConfig);
let frontComponent = computed(() => {
  let tray = store.getCurrentTray;
  return tray.frontComponentList;
});
let oppositeComponent = computed(() => {
  let tray = store.getCurrentTray;
  return tray.oppositeComponentList;
});
let trayStyle = computed(() => (t) => {
  let backgroundImage = "";
  if (t == 0) {
    //正面
    backgroundImage = trayConfig.value.frontImg
      ? `url(${trayConfig.value.frontImg})`
      : `url(${trayImg})`;
  } else {
    backgroundImage = trayConfig.value.oppositeImg
      ? `url(${trayConfig.value.oppositeImg})`
      : `url(${trayImg})`;
  }
  return {
    backgroundImage,
    width: trayConfig.value.trayLong + "px",
    height: trayConfig.value.trayWidth + "px",
    // backgroundSize: "cover",
  };
});
let canvasStyle = computed(() => {
  let trayBlock = store.getTrayBlockSize;
  return {
    width: trayBlock.width + "px",
    height: trayBlock.height + "px",
  };
});

const drag_key = "drag_key";
function dragHandle(e, side) {
  let drayDataString = e.dataTransfer.getData(drag_key);
  if (!drayDataString) return;
  let { offsetX, offsetY } = e;
  let materia = JSON.parse(drayDataString);
  materia.id = getGUID();

  materia.x = +offsetX.toFixed(2);
  materia.y = +offsetY.toFixed(2);
  materia.position = side;
  //盘袋盒箱 0-其他 1-盘 2-袋 3-盒 4-箱 5-托盘
  materia.reelType = 5;
  store.addComponent(materia, side);
  store.changeSelectedComponent(materia);
}

function dragoverHandle(e) {
  e.preventDefault();
  e.stopPropagation();
  if (e.dataTransfer) e.dataTransfer.dropEffect = "copy";
}

function clickHandle() {
  store.changeSelectedComponent({ id: "tray", type: "tray" });
  selectTie.value = {};
  menuShow.value = false;
}

let tieStart = { tx: 0, ty: 0, sx: 0, sy: 0, type: "x" };
function tieDown(e, tie, type) {
  selectTie.value = tie;
  let { screenX, screenY } = e;
  tieStart = { tx: tie.x, ty: tie.y, sx: screenX, sy: screenY, type };
  document.body.addEventListener("mousemove", tieMove);
}
function tieMove(e) {
  if (selectTie.value.lock) return;
  let { screenX, screenY } = e;
  let { tx, ty, sx, sy, type } = tieStart;
  let scale = trayConfig.value.scale;
  if (type == "x") {
    selectTie.value.y = ty + ((screenY - sy) / scale) * 100;
    if (selectTie.value.y <= 0) {
      selectTie.value.y = 0;
    } else if (
      selectTie.value.y >=
      trayConfig.value.trayWidth - trayConfig.value.tieWidth
    ) {
      selectTie.value.y =
        trayConfig.value.trayWidth - trayConfig.value.tieWidth;
    }
  } else if (type == "y") {
    selectTie.value.x = tx + ((screenX - sx) / scale) * 100;
    if (selectTie.value.x <= 0) {
      selectTie.value.x = 0;
    } else if (
      selectTie.value.x >=
      trayConfig.value.trayLong - trayConfig.value.tieWidth
    ) {
      selectTie.value.x = trayConfig.value.trayLong - trayConfig.value.tieWidth;
    }
  }
}
function tieUp() {
  document.body.removeEventListener("mousemove", tieMove);
}
function handleContextmenu(e) {
  e.preventDefault();
  e.stopPropagation();
  menuShow.value = true;
  position.left = e.pageX + 3 + "px";
  position.top = e.pageY + "px";
}
function changeLock() {
  selectTie.value.lock = !selectTie.value.lock;
  menuShow.value = false;
}

onMounted(() => {
  document.body.addEventListener("click", handleClick);
});

function handleClick(e) {
  let node = e.target.closest("#tie-menu");
  if (!node && menuShow.value) {
    menuShow.value = false;
  }
  if (selectTie.value.id) {
    selectTie.value = {};
  }
}
onBeforeMount(() => {
  document.body.removeEventListener("click", handleClick);
});
</script>
<style scoped lang="scss">
.tray-info {
  flex: 1;
  overflow: auto;
  .scale-block {
    overflow: auto;
    transform-origin: 0 0;
  }
  .tray {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    z-index: 0;
    background-size: 100% 100%;
    // border: 1px solid rgb(67, 85, 133);
  }
  .canvas {
    background-color: rgba(214, 220, 242, 0.4);
    position: relative;
    margin: 10px 20px 80px 80px;
    .tip {
      position: absolute;
      top: 5px;
      left: 5px;
      color: #000;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .tray-tie {
    position: relative;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    .tie-x {
      position: absolute;
      background-color: rgba(0, 0, 0, 0.5);
      width: 100%;
      z-index: 99;
    }
    .tie-y {
      position: absolute;
      background-color: rgba(0, 0, 0, 0.5);
      height: 100%;
      z-index: 100;
    }
    .selected {
      border: 1px dashed #15f47d;
    }
  }
}
.r-menu {
  position: fixed;
  width: 110px;
  padding: 5px 10px;
  z-index: 99999;
  background-color: rgb(72, 72, 78);
  border-radius: 5px;
  .item {
    width: 100%;
    height: 28px;
    display: flex;
    align-items: center;
    color: #eee;
    cursor: pointer;
    .icon {
      width: 16px;
      margin-right: 10px;
    }
    .label {
      font-size: 14px;
    }
  }
}
</style>
